package com.dev.drawweb.controller;
import com.dev.drawweb.model.pojo.Draw;
import com.dev.drawweb.model.pojo.Manager;
import com.dev.drawweb.model.pojo.Student;
import com.dev.drawweb.model.service.DrawService;
import com.dev.drawweb.model.service.ManagerService;
import com.dev.drawweb.model.service.StudentService;
import com.dev.drawweb.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
public class TotalController {
    @Autowired
    ManagerService managerService;

    @Autowired
    StudentService studentService;

    @Autowired
    DrawService drawService;

    public String noSuchJur(Model model){
        model.addAttribute("errorMsg","您没有权限");
        return "errorPage";
    }

    public String drawNameJurCheck(String drawName,HttpServletRequest request,Model model){
        int userId=((Manager)request.getSession().getAttribute("manaMsg")).getUserid();
        if(!SecurityUtil.manaJurCheck(userId,drawName)){
            return noSuchJur(model);
        }
        return null;
    }

    @RequestMapping("/toStudentLogin")
    public String toStudentLogin(Model model){
        model.addAttribute("errorMsg","");
        return "Login_Page_Student";
    }

    @RequestMapping("/toTeacherLogin")
    public String toTeacherLogin(Model model){
        model.addAttribute("errorMsg","");
        return "Login_Page_Teacher";
    }

    @RequestMapping("/stuLogin/toReSetPage")
    public String toReSetPage(Model model){
        model.addAttribute("errorMsg","");
        return "StuReSetPage";
    }

    @RequestMapping(value = "/stuLogin/doReSetPW",method = RequestMethod.POST)
    public String doReSetPW(String newPW,String confirmPW,Model model,HttpServletRequest request){
        int stuId=((Student)request.getSession().getAttribute("stuMsg")).getStuid();
        try{
            if(newPW.equals(confirmPW)){
                studentService.updateStuPassword(stuId,newPW);
                return "forward:/stuLogin/toStuDefenses";
            }
            throw new Exception();
        }
        catch (Exception e){
            model.addAttribute("errorMsg","密码不一致");
            return "StuReSetPage";
        }
    }

    @RequestMapping(value = "/Student/login",method = RequestMethod.POST)
    public String studentLogin(int stuId,String passWord,HttpServletRequest httpServletRequest,Model model){
        try{
            Student student=studentService.getStudentById(stuId);
            if(student.getPassword().equals(passWord)){
                httpServletRequest.getSession().setAttribute("stuMsg",student);
                if(passWord.equals(String.valueOf(stuId))){
                    return "forward:/stuLogin/toReSetPage";
                }
                return "forward:/stuLogin/toStuDefenses";
            }
            throw new Exception();
        }
        catch (Exception e){
            model.addAttribute("errorMsg","用户名或密码错误");
            return "Login_Page_Student";
        }
    }

    @RequestMapping(value = "/Manager/login",method = RequestMethod.POST)
    public String managerLogin(int userId,String passWord,HttpServletRequest httpServletRequest,Model model){
        try {
            Manager manager = managerService.getManagerByID(userId);
            if (manager.getPassword().equals(passWord)) {
                httpServletRequest.getSession().setAttribute("manaMsg", manager);
                return "forward:/manaLogin/toDenfense_List";
            }
            throw new Exception();
        }
        catch (Exception e) {
            model.addAttribute("errorMsg","用户名或密码错误");
            return "Login_Page_Teacher";
        }
    }

    @RequestMapping("/stuLogin/toStuDefenses")
    public String toStuDefenses(Model model,HttpServletRequest request){
        int stuId=((Student)request.getSession().getAttribute("stuMsg")).getStuid();
        List<Map> draws=drawService.getDrawsByStuID(stuId);
        Student student=studentService.getStudentById(stuId);
        model.addAttribute("draws",draws);
        model.addAttribute("stuName",student.getStuname());
        return "StuDefenses";
    }

    @RequestMapping("/manaLogin/toDenfense_List")
    public String toDenfenseList(Model model,HttpServletRequest request){
        int userId=((Manager)request.getSession().getAttribute("manaMsg")).getUserid();
        Manager manager=managerService.getManagerByID(userId);
        List<Draw> draws=drawService.getDrawsByUserID(userId);
        model.addAttribute("user",manager);
        model.addAttribute("draws",draws);
        return "Denfense_List";
    }

    @RequestMapping("/manaLogin/toAddDefense")
    public String toAddDefense(Model model,HttpServletRequest request){
        int userId=((Manager)request.getSession().getAttribute("manaMsg")).getUserid();
        model.addAttribute("errorMsg","");
        return "Add_Defense";
    }

    @RequestMapping(value = "/manaLogin/addDefense",method=RequestMethod.POST)
    public String addDenfense(String defenseName,Model model,HttpServletRequest request){
        int userId=((Manager)request.getSession().getAttribute("manaMsg")).getUserid();
        try{
            drawService.addDraw(userId,defenseName);
            return "redirect:/manaLogin/toDenfense_List";
        }
        catch (Exception e){
            model.addAttribute("errorMsg","答辩已存在");
            return "Add_Defense";
        }
    }

    @RequestMapping("/manaLogin/toDefenseOrder/{drawName}/{mod}")
    public String toDefenseOrder(@PathVariable String drawName,@PathVariable int mod,Model model,HttpServletRequest request){
        String errorPage=drawNameJurCheck(drawName, request, model);
        if(errorPage!=null){return errorPage;}
        List<Student> students=drawService.defenseOrderService(drawName,mod);
        model.addAttribute("students",students);
        model.addAttribute("drawName",drawName);
        return "Defense_Order";
    }

    @RequestMapping(value = "/stuLogin/doStuDraw",method = RequestMethod.POST)
    public String doStuDraw(String drawname,int tmpDrawRes,HttpServletRequest request){
        int stuid=((Student)request.getSession().getAttribute("stuMsg")).getStuid();
        if(tmpDrawRes==-1) {
            drawService.doStuDraw(drawname, stuid);
        }
        return "forward:/stuLogin/toStuDefenses";
    }

    @RequestMapping("/manaLogin/delFromUser/{drawName}")
    public String delFromUser(@PathVariable String drawName,Model model,HttpServletRequest request){
        int userId=((Manager)request.getSession().getAttribute("manaMsg")).getUserid();
        if(!SecurityUtil.manaJurCheck(userId,drawName)){
            return noSuchJur(model);
        }
        try {
            drawService.delFromUser(userId,drawName);
        }
        catch (Exception e){}
        finally {
            return "forward:/manaLogin/toDenfense_List";
        }
    }

    @RequestMapping("/manaLogin/delFromDraw/{drawName}/{stuId}")
    public String delFromDraw(@PathVariable String drawName,@PathVariable int stuId,HttpServletRequest request,Model model){
        String errorPage=drawNameJurCheck(drawName, request, model);
        if(errorPage!=null){return errorPage;}
        try {
            drawService.delFormDraw(stuId, drawName);
        }
        catch (Exception e){}
        finally {
            return "forward:/manaLogin/toDefenseOrder/"+drawName+"/0";
        }
    }

    @RequestMapping(value = "/manaLogin/addStuToDraw",method=RequestMethod.POST)
    public String addStuToDraw(String drawName,int stuId,String stuName,String major,Model model,HttpServletRequest request){
        String errorPage=drawNameJurCheck(drawName, request, model);
        if(errorPage!=null){return errorPage;}
        Student student = studentService.getStudentById(stuId);
        try {
            if (student == null || student.getStuname().equals(stuName) && student.getMajor().equals(major)) {
                if (student == null) {
                    studentService.addStudent(new Student(stuId, String.valueOf(stuId), stuName, major));
                }
                drawService.addStudentToDraw(drawName, stuId);
                return "forward:/manaLogin/toDefenseOrder/" + drawName + "/0";
            }
        }
        catch (Exception e) {}
        model.addAttribute("errorMsg", "学生已存在，或信息有误。");
        model.addAttribute("drawName", drawName);
        return "Add_Student";
    }

    @RequestMapping("/manaLogin/toAddStudent/{drawName}")
    public String toAddStudent(@PathVariable String drawName,Model model,HttpServletRequest request){
        String errorPage=drawNameJurCheck(drawName, request, model);
        if(errorPage!=null){return errorPage;}
        model.addAttribute("errorMsg","");
        model.addAttribute("drawName",drawName);
        return "Add_Student";
    }

    @RequestMapping(value = "manaLogin/updateScore",method = RequestMethod.POST)
    public String updateStuScore(String drawName,int stuId,String newScore,Model model,HttpServletRequest request){
        String errorPage=drawNameJurCheck(drawName, request, model);
        if(errorPage!=null){return errorPage;}
        try {
            drawService.upDateStuScore(drawName, stuId, Integer.valueOf(newScore));
        }
        catch (Exception e){}
        finally {
            return "forward:/manaLogin/toDefenseOrder/"+drawName+"/0";
        }
    }

    @RequestMapping("/manaLogin/download/{drawName}")
    public String downloadFile(@PathVariable String drawName, Model model, HttpServletResponse response,HttpServletRequest request) {
        String errorPage=drawNameJurCheck(drawName, request, model);
        if(errorPage!=null){return errorPage;}
        String fileName=drawName+DrawService.drawDescrib+".csv";
        try{
            drawService.writeDrawFile(drawName);
            drawService.doDownLoadFile(fileName,response);
        } catch (Exception e) {
            model.addAttribute("errorMsg","下载失败");
            return "errorPage";
        }
        return "forward:/manaLogin/toDefenseOrder/"+drawName+"/0";
    }

    @RequestMapping("/manaLogin/toConfigEmail/{drawName}")
    public String toConfigEmail(@PathVariable String drawName,Model model,HttpServletRequest request){
        String errorPage=drawNameJurCheck(drawName, request, model);
        if(errorPage!=null){return errorPage;}
        model.addAttribute("drawName",drawName);
        return "configEmail";
    }

    @RequestMapping(value = "/manaLogin/email",method = RequestMethod.POST)
    public String emailFile(String drawName,String toEmail, Model model,HttpServletRequest request){
        String errorPage=drawNameJurCheck(drawName, request, model);
        if(errorPage!=null){return errorPage;}
        try{
            drawService.writeDrawFile(drawName);
            drawService.doSendEmailFile(drawName,toEmail);
        } catch (Exception e) {
            model.addAttribute("errorMsg","发送失败");
            return "errorPage";
        }
        return "forward:/manaLogin/toDefenseOrder/"+drawName+"/0";
    }

    @RequestMapping("/toManaRegister")
    public String toManaRegister(Model model){
        model.addAttribute("errorMsg","");
        return "Register_Page_Teacher";
    }

    @RequestMapping(value = "registerMana",method = RequestMethod.POST)
    public String registerMana(int userId,String userName,String passWord,Model model){
        try {
            managerService.addManager(new Manager(userId,userName,passWord));
            return "Login_Page_Teacher";
        }
        catch (Exception e){
            model.addAttribute("errorMsg","账号已存在");
            return "Register_Page_Teacher";
        }
    }


}
